


package leetcode.other.p128;

import java.util.HashSet;
import java.util.Set;

class Solution2 {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }

        int m = set.size();
        int ans = 0;

        for (int x : nums) {
            if (set.contains(x - 1)) {
                continue;
            }
            int y = x + 1;
            while(set.contains(y)) {
                y++;
            }
            ans = Math.max(ans, y - x);
            if (ans * 2 >= m) {
                break;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        // 示例 1：
        // 输入：nums = [100,4,200,1,3,2]
        // 输出：4
        System.out.println(new Solution().longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}));
        // 解释：最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
        // 示例 2：
        // 输入：nums = [0,3,7,2,5,8,4,6,0,1]
        // 输出：9
        System.out.println(new Solution().longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}));
        // 示例 3：
        // 输入：nums = [1,0,1,2]
        // 输出：3
        System.out.println(new Solution().longestConsecutive(new int[]{1, 0, 1, 2}));
        System.out.println(new Solution2().longestConsecutive(new int[]{9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6}));
    }
}